import _ from 'lodash';
import { useEffect, useState } from 'react';
import { roleService, userService } from '@/utils/leancloud-helper';
import { Button, Input, Picker, Toast, Space, Dialog, Tag, Selector } from 'antd-mobile';
import { EditSFill, DeleteOutline, UserOutline } from 'antd-mobile-icons';
import emitter from '@/utils/mybus'

export default () => {
  useEffect(() => {
    syncRoles();
    syncUsers();
    emitter.on('syncRoles',()=>{
      syncRoles();
    })
  }, []);

  const initUser = { name: '', roleId: [''] };
  const [user, setUser] = useState(_.cloneDeep(initUser));
  const [visible, setVisible] = useState(false);
  const [roles, setRoles] = useState([]);
  const [users, setUsers] = useState([]);

  const syncUsers = async (roleIds) => {
    const res = await userService.query(roleIds);
    setUsers(res);
  };

  const syncRoles = async () => {
    const res = await roleService.query();
    setRoles(res.map((it) => ({ value: it.id, label: it.attributes.name })));
  };

  const onConfirm = async () => {
    if (user.id) {
      await userService.update(user);
    } else {
      await userService.save(user);
    }
    Toast.show({
      icon: 'success',
      content: '保存成功',
      afterClose() {
        setVisible(false);
        syncUsers();
      }
    });
  };

  const onAddOrEdit = async (item) => {
    setUser(item ? { id: item.id, name: item.attributes.name, roleId: [item.attributes.role.id] } : _.cloneDeep(initUser));
    if (item) {
      await syncRoles();
    }
    setVisible(true);
  };

  const onRemove = async (id) => {
    await userService.remove(id);
    syncUsers();
  };


  const onSelector = (arr, extend) => {
    syncUsers(arr);
  }


  return (
    <>
      <Button
        size="small"
        color="primary"
        fill="solid"
        onClick={() => {
          onAddOrEdit();
        }}>
        <UserOutline /> 创建用户
      </Button>

      <div className='selector-role'>
        <Selector options={roles} multiple={true} onChange={onSelector} />
      </div>
      
      <div className="users">
        
        {users.map((item, index) => (
          <div className="role" key={item.id}>
            <Space>
              <span>{index+1} {item.attributes.name} </span>
              <Tag color="#2db7f5">{item.attributes.role.attributes.name}</Tag>
            </Space>
            <Space>
              <EditSFill
                onClick={() => {
                  onAddOrEdit(item);
                }}
              />
              <DeleteOutline
                onClick={() => {
                  Dialog.confirm({
                    content: '确定删除？',
                    onConfirm: async () => {
                      await onRemove(item.id);
                    }
                  });
                }}
              />
            </Space>
          </div>
        ))}
      </div>
      <Dialog
        title={user?.id ? '编辑用户' : '创建用户'}
        visible={visible}
        content={
          <>
            <div className="dialog-form">
              <span>所属角色</span>
              <Picker
                columns={[roles]}
                value={user.roleId}
                onConfirm={(v) => {
                  user.roleId = v;
                  setUser({ ...user });
                }}>
                {(items, { open }) => {
                  return (
                    <Space align="center">
                      <Input
                        placeholder="请选择"
                        value={items.every((item) => item === null) ? '' : items.map((item) => item?.label ?? '').join(' - ')}
                        onClick={() => {
                          syncRoles();
                          open();
                        }}
                      />
                    </Space>
                  );
                }}
              </Picker>
            </div>

            <div className="dialog-form">
              <span>用户名</span>
              <Input
                placeholder="请输入"
                value={user.name}
                onChange={(val) => {
                  user.name = val;
                  setUser({ ...user });
                }}
              />
            </div>

            <div className="addrole-actions">
              <Button
                color="success"
                fill="solid"
                onClick={() => {
                  onConfirm();
                }}>
                提交
              </Button>
              <Button
                fill="outline"
                onClick={() => {
                  setVisible(false);
                }}>
                取消
              </Button>
            </div>
          </>
        }
        onClose={() => {
          setVisible(false);
        }}
      />
    </>
  );
};
